<template>
  <div class="comment">
    <div class="comment-time">
      {{commentItem.time | formatDate}}
      <span class="comment-more"
            v-if="hasKids"
            @click="open=!open">[{{
        open
          ? '-'
          : commentItem.kids.length+'more'
        }}]</span>
    </div>
    <div class="comment-text">{{commentItem.text}}</div>
    <div class="comment-apply">
      <button class="comment-apply-check"
              @click="showApply=!showApply">
        apply
      </button>
      <template v-if="showApply">
        <input type="text"
               class="comment-apply-input"
               v-model="text">
        <button @click="apply">send</button>
      </template>
    </div>
    <div class="comment-kids"
         v-if="hasKids&&open">
      <comment v-for="i in commentItem.kids"
               :id="i"
               :key="i"></comment>
    </div>
  </div>
</template>

<script>
export default {
  name: 'comment',
  data () {
    return {
      open: true,
      showApply: false,
      text: ''
    }
  },
  props: ['id'],
  computed: {
    allCommentList: {
      get () {
        return this.$store.state.allCommentList
      },
      set (value) {
        this.$store.commit('changeState', {
          prop: 'allCommentList',
          value
        })
      }
    },
    hasKids () {
      return this.commentItem.kids && this.commentItem.kids.length
    },
    commentItem () {
      return this.$store.state.allCommentList.find(({ id }) => id === this.id)
    },
  },
  filters: {
    formatDate: function (val) {
      const value = new Date(val);
      const year = value.getFullYear();
      const month = value.getMonth() + 1;
      const day = (value.getDate());
      return year + '-' + (month >= 10 ? month : '0' + month) + '-' + (day >= 10 ? day : '0' + day);
    }
  },
  methods: {
    apply () {
      const { text, id, allCommentList } = this
      const newId = allCommentList.length + 1
      allCommentList.push({
        id:newId,
        text,
        time: new Date().getTime(),
        kids: []
      })
      allCommentList.some((comment, index) => {
        if (comment.id === id) {
          allCommentList[index].kids = [...comment.kids, newId]
          return true
        }
      })
      Object.assign(this, {
        text: '',
        showApply: false,
      })
    }
  }
}
</script>

<style lang="scss">
.comment {
  &-time {
    color: #828282;
  }
  &-more {
    cursor: pointer;
  }
  &-kids {
    margin-left: 20px;
  }
  &-apply {
    color: #828282;
  }
}
</style>